<template>
  <div class="">-{{ data }}</div>
</template>

<script setup>
import { ref } from 'vue';
const data = ref('');
let timer;
const wsIns = new WebSocket('wss://broadcastlv.chat.bilibili.com:443/sub');
var certification = {
  uid: 0,
  roomid: '31399819',
  protover: 3,
  platform: 'web',
  type: 2,
  key: '', //值为空字符串好像也没问题
};
//生成认证数据
const getCertification = (json) => {
  let encoder = new TextEncoder(); //编码器
  let jsonView = encoder.encode(json); //utf-8编码
  let buff = new ArrayBuffer(jsonView.byteLength + 16); //数据包总长度：16位头部长度+bytes长度
  let view = new DataView(buff); //新建操作视窗
  view.setUint32(0, jsonView.byteLength + 16); //整个数据包长度
  view.setUint16(4, 16); //头部长度
  view.setUint16(6, 1); //协议版本
  view.setUint32(8, 7); //类型,7为加入房间认证
  view.setUint32(12, 1); //填1
  for (let r = 0; r < jsonView.byteLength; r++) {
    view.setUint8(16 + r, jsonView[r]); //填入数据
  }
  return buff;
};
wsIns.onopen = () => {
  console.log('连接成功');
  wsIns.send(getCertification(JSON.stringify(certification)));
  //发送心跳包
  timer = setInterval(function () {
    let buff = new ArrayBuffer(16);
    let i = new DataView(buff);
    i.setUint32(0, 0); //整个封包
    i.setUint16(4, 16); //头部
    i.setUint16(6, 1); //协议版本
    i.setUint32(8, 2); //操作码,2为心跳包
    i.setUint32(12, 1); //填1
    ws.send(buff);
  }, 30000); //30秒
};

wsIns.onmessage = (e) => {
  console.log(e, '收到消息--');
  if (e.data) {
    console.log(e.data, '收到消息');
    data.value = e.data;
  }
};
wsIns.onclose = () => {
  timer && clearInterval(timer);
};
</script>

<style lang="scss"></style>
